package com.primaryAlgorithm;

import com.lx.algorithm.LinkedList.NodeTest1;

/**
 * Description: 删除链表的某个节点
 * Copyright:   Copyright (c)2019
 * Company:     zefu
 *
 * @author: 张李鑫
 * @version: 1.0
 * Create at:   2021-09-26 00:17:04
 * <p>
 * Modification History:
 * Date         Author      Version     Description
 * ------------------------------------------------------------------
 * 2021-09-26     张李鑫                     1.0         1.0 Version
 */
public class RemoveNthFromEnd {

    public static class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }
    }

    public static ListNode removeNthFromEnd(ListNode head, int n) {
        if (head == null) {
            return null;
        }
        ListNode node = reverseNode(head);
        if (n == 1) {
            node = node.next;
        } else {
            ListNode p = node;
            for (int i = 1; i < n - 1; i++) {
                p = p.next;
            }
            p.next =  p.next.next;

        }
        return reverseNode(node);
    }

    public static ListNode reverseNode(ListNode node) {
        ListNode oldNode = null;
        ListNode newNode = null;
        while (node != null) {
            newNode = node.next;
            node.next = oldNode;
            oldNode = node;
            node = newNode;
        }
        return oldNode;
    }

    public static void main(String[] args) {
        ListNode node = new ListNode(1);
        ListNode node1 = new ListNode(2);
        ListNode node2 = new ListNode(3);
        ListNode node3 = new ListNode(4);
        ListNode node4 = new ListNode(5);

        node.next = node1;
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        ListNode node5 = removeNthFromEnd(node, 2);
        System.out.println(123);

    }
}